package com.tzm.gaflow.strategy.route;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tzm.gaflow.consts.FlowNames;
import com.tzm.gaflow.dto.GaBusinessDTO;
import com.tzm.gaflow.entity.GaFlowInfo;
import com.tzm.gaflow.entity.GaFlowMain;
import com.tzm.gaflow.entity.GaFlowTasklog;
import com.tzm.gaflow.strategy.TaskExecuteRoute;


public class TaskExecuteBack extends TaskExecuteRoute {

    @Override
    public GaFlowTasklog route(GaBusinessDTO gaBusinessDTO, GaFlowMain gaFlowMain) {
        long between = 0L;
        if (ObjectUtil.isEmpty(gaFlowMain.getHandleTime())) {
            between = DateUtil.between(DateUtil.parseDateTime(DateUtil.now()), gaFlowMain.getApplyTime(), DateUnit.SECOND);
        } else {
            between = DateUtil.between(DateUtil.parseDateTime(DateUtil.now()), gaFlowMain.getHandleTime(), DateUnit.SECOND);
        }

        if (StrUtil.isBlank(gaFlowMain.getPreviousFlowId())) { //end
            gaFlowMain.setTaskState(FlowNames.TASKSTATE_END);
            gaFlowMain.setContent(gaBusinessDTO.getContent());
            gaFlowMain.setHandleTime(DateUtil.parseDateTime(DateUtil.now()));
            gaFlowMain.setCompleteTime(DateUtil.parseDateTime(DateUtil.now()));
            gaFlowMain.setRemark("流程任务回退终止");
            gaFlowMain.updateById();
        } else {//back
            GaFlowInfo PreGaFlowInfo = new GaFlowInfo().selectById(gaFlowMain.getPreviousFlowId());
            gaFlowMain.setTaskState(FlowNames.TASKSTATE_RUN);
            gaFlowMain.setContent(gaBusinessDTO.getContent());
            gaFlowMain.setHandleTime(DateUtil.parseDateTime(DateUtil.now()));
            gaFlowMain.setPreviousFlowId(PreGaFlowInfo.getPreviousFlowId());
            gaFlowMain.setPreviousFlowName(PreGaFlowInfo.getPreviousFlowName());
            gaFlowMain.setFlowId(PreGaFlowInfo.getFlowId());
            gaFlowMain.setFlowName(PreGaFlowInfo.getFlowName());
            gaFlowMain.setNextFlowId(PreGaFlowInfo.getNextFlowId());
            gaFlowMain.setNextFlowName(PreGaFlowInfo.getNextFlowName());
            gaFlowMain.setRemark("流程任务运行");
            gaFlowMain.updateById();
        }
        //log
        GaFlowTasklog gaFlowTasklog = new GaFlowTasklog();
        BeanUtil.copyProperties(gaFlowMain, gaFlowTasklog);
        gaFlowTasklog.setUseTime(Convert.toStr(between));
        gaFlowTasklog.setCreateTime(DateUtil.parseDateTime(DateUtil.now()));
        return gaFlowTasklog;
    }
}
